package com.hjt.frame;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;

import javax.swing.JFrame;
import com.hjt.adb.utils.DeviceUtil;
import com.hjt.db.DBManager;
import com.hjt.db.DBManager.RequestParam;
import com.hjt.utils.FileUtil;
import com.hjt.utils.Util;

public class DataCollectFrame extends JFrame {	
	private static final long serialVersionUID = 1L;
	private Robot robot;
	private JFrame f;


	public DataCollectFrame() {
		try {
			robot = new Robot();
		} catch (AWTException e1) {
			e1.printStackTrace();
		}		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setUndecorated(true);
		this.setBackground(new Color(0,0,0,0.1f));
		this.setBounds(73, 181, 960, 540);
		this.setVisible(true);
		this.addMouseListener(new MouseAdapter() {
			long pressedTime;
			long releasedTime;
			@Override
			public void mouseReleased(MouseEvent e) {
				releasedTime = System.currentTimeMillis();
			}
			@Override
			public void mousePressed(MouseEvent e) {
				pressedTime = System.currentTimeMillis();
			}
			@Override
			public void mouseClicked(MouseEvent e) {
				saveFile(e.getPoint());
				f.setVisible(false);
				Util.sleepRandom(140);
				robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
				long dis = releasedTime - pressedTime;
				if(dis > 0 && dis < 200) {
					Util.sleep(dis);
				}else {
					Util.sleep(40);
				}
				robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
				f.setVisible(true);
			}
		});
		f = this;
	}
	
	private void saveFile(Point point) {
		new Thread(() -> {
			List<String> deviceIds = DeviceUtil.devices();
			String deviceId = deviceIds.get(0);
			BufferedImage buff = DeviceUtil.screenCap(deviceId);
			File f = FileUtil.createImgAndPoint(buff, point);
			RequestParam req = new RequestParam();
			req.setDeviceId(deviceId);
			req.setImgData(FileUtil.readBytesFromFile(f));
			req.setName(f.getName());
			req.setPointX(point.getX());
			req.setPointY(point.getY());
			req.setPath(f.getAbsolutePath());
			DBManager.createRecord(req);
		}).start();
	}
	
	public static void main(String[] args) {
		new DataCollectFrame();
	}
}
